#include<vector>
#include<string>
#include<iostream>
using namespace std;


// 这里不需要每次都新建一个flag数组，直接传引用即可
// 每次都会恢复现场的。
class Solution {
public:
    bool res = false;
    int dx[4] = {-1, 1, 0, 0};
    int dy[4] = {0, 0, -1, 1};
    
    void dfs(vector<vector<char>>& board, int i, int j, string& word, int m, int n, int idx, vector<vector<bool>>& flag) {
        if (idx == word.size()) {
            res = true;
            return;
        }
        if (i < 0 || i >= m || j < 0 || j >= n) return;
        if (board[i][j] != word[idx] || flag[i][j]) return;

        flag[i][j] = true;
        for (int k = 0; k < 4; k++) {
            dfs(board, i + dx[k], j + dy[k], word, m, n, idx + 1, flag);
            if (res) return;
        }
        flag[i][j] = false;
    }

    bool exist(vector<vector<char>>& board, string word) {
        int m = board.size();
        int n = board[0].size();
        vector<vector<bool>> flag(m, vector<bool>(n, false));

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                dfs(board, i, j, word, m, n, 0, flag);
                // 因为dfs有恢复现场，所以出来之后的flag也是初始状态
                if (res) return true;
            }
        }
        return false;
    }
};
